import Vue from "vue";
import Vuex from "vuex";
import { getMenuList } from "../api/permisstion";
import recursionRoutes from "../axios/recursionRoute";
//引入所有的路由
import result from "../router/generaterouters";
//引入动态路由
import dynamicroutes from "../router/dynamicroutes";

import lodash from "lodash";

import router from "../router";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userMenu: [],
    userInfo: {},
    currentproduct: {},
  },
  getters: {},
  mutations: {
    //设置用户菜单
    SET_MENULIST(state, payload) {
      let target = dynamicroutes.find((route) => route.path == "/");
      state.userMenu = [...payload];
      // 浅拷贝

      //动态添加路由,引入dynamic路由,进行匹配,匹配到path=='/'这个对象,让我们的用户路由中的结果，成为这个对象的children

      target.children = [...target.children, ...payload];
      //动态的将陆游添加到路由的router中

      router.addRoute(target);
      // router.addRoute动态添加路由，参数是一个对象，这个对象必须符合routes的配置
    },
    SET_USERINFO(state, payload) {
      state.userInfo = payload;
    },
    SET_CURRENTPRODUCT(state, payload) {
      state.currentproduct = payload;
    },
  },
  actions: {
    async FETCH_MENULIST(context, payload) {
      // 请求菜单数据，根据菜单数据 计算role角色的菜单，计算这个角色的合法路由
      return getMenuList().then((res) => {
        //后台返回的菜单数据
        let { menuList } = res.data;
        // console.log("后台返回的菜单数据", menuList);
        let userroutes = recursionRoutes(result[0].children, menuList);
        // console.log("要给state的数据userroutes", userroutes);
        // console.log("这个是系统的所有路由result", result);

        context.commit("SET_MENULIST", userroutes);
      });
    },
  },
  modules: {},
});
